const { join, extname } = require('path')
const fs = require('fs')
const http = require('http')
const { createGzip } = require('zlib')
const mimes = require('./libs/mime')

const webRoot=join(__dirname,'www');
http.createServer((req,res)=>{
  if(req.url!='/favicon.ico'){
    let pathname = req.url === '/' ? '/index.html' : req.url;
    let filepath = join(webRoot, pathname);
    //判断文件是否存在
    if(fs.existsSync(filepath)){
      //得到请求文件的扩展名
      const ext=extname(filepath).slice(1);
      const mime=mimes[ext];

      //设置响应头
      res.setHeader('content-type', mime)
      //读取文件并给响应
      res.end(fs.readFileSync(filepath))
      if(res.headers['content-type']='image/jpeg'){
        res.setHeader('data')
      }

    }else{
      res.statusCode=404;
    
      res.end('not found')
    }
  }
}).listen(3000, '0.0.0.0',()=>{
  console.log('服务器已启动')
})